/**
 * created by 小卷毛, 2023-05-26
 * Copyright (c) 2023, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.picture

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.TextPaint
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.interfaces.OnBitmapWatermarkEventListener
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.PictureFileUtils
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.getTimeString
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.abs
import kotlin.math.ceil


/**
 * 描 述：
 * 作 者：小卷毛  2023-05-26 17:40
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class PictureMarkEvent(
    private val targetPath: String
) : OnBitmapWatermarkEventListener {

    override fun onAddBitmapWatermark(
        context: Context,
        srcPath: String,
        mimeType: String,
        call: OnKeyValueResultCallbackListener?
    ) {
        (PictureMimeType.isHasHttp(srcPath)
                || PictureMimeType.isHasVideo(mimeType)).conditionElse(
            // 忽略网络图片和视频
            actionTrue = {
                call?.onCallback(srcPath, "")
            },
            // 图片加水印
            actionFalse = {
                Glide.with(context)
                    .asBitmap()
                    .sizeMultiplier(0.6f)
                    .load(srcPath)
                    .into(object : CustomTarget<Bitmap?>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap?>?
                        ) {
                            val stream = ByteArrayOutputStream()
                            val markBitmap = buildBitmap(resource)
                            markBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
                            markBitmap.recycle()

                            var fos: FileOutputStream? = null
                            var result: String? = null
                            try {
                                val targetFile =
                                    File(targetPath, DateUtils.getCreateFileName("Mark_") + ".jpg")
                                fos = FileOutputStream(targetFile)
                                fos.write(stream.toByteArray())
                                fos.flush()

                                result = targetFile.absolutePath
                            } catch (e: IOException) {
                                e.printStackTrace()
                            } finally {
                                PictureFileUtils.close(fos)
                                PictureFileUtils.close(stream)
                            }

                            call?.onCallback(srcPath, result)
                        }

                        /**
                         * 生成水印图片
                         */
                        private fun buildBitmap(bitmap: Bitmap): Bitmap {
                            val newBitmap = Bitmap
                                .createBitmap(
                                    bitmap.width,
                                    bitmap.height,
                                    Bitmap.Config.ARGB_8888
                                )

                            val hint = System
                                .currentTimeMillis()
                                .getTimeString()

                            val marginLR = dp2px(5f).toFloat()

                            val textPaint = TextPaint()
                                .apply {
                                    color = Color.WHITE
                                    textSize = dp2px(14f).toFloat()
                                }

                            val fontMetrics = textPaint.fontMetrics
                            val width = ceil(
                                textPaint.measureText(hint)
                            ).toInt()
                            val height = ceil(
                                abs(fontMetrics.bottom)
                                        + abs(fontMetrics.top)
                            ).toInt()

                            val maskPaint = Paint()
                                .apply {
                                    color = Color.parseColor("#B3000000")
                                }

                            Canvas(newBitmap).apply {
                                // 绘制原图
                                val rect = Rect(0, 0, bitmap.width, bitmap.height)
                                drawBitmap(bitmap, rect, rect, null)

                                // 绘制蒙层
                                drawRect(
                                    0f,
                                    (bitmap.height - height).toFloat(),
                                    width + marginLR * 2,
                                    bitmap.height.toFloat(),
                                    maskPaint
                                )

                                // 绘制文本
                                drawText(
                                    hint,
                                    marginLR,
                                    bitmap.height - height + abs(fontMetrics.ascent),
                                    textPaint
                                )

                                save()
                                restore()
                            }

                            return newBitmap
                        }

                        override fun onLoadCleared(placeholder: Drawable?) {
                            call?.onCallback(srcPath, "")
                        }
                    })
            }
        )
    }

}